define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    
    
    require('page/js/frame/leftmenu/ambassadorCalendarCtrl');
    
    var scheduleService = require('scheduleService');
    var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil');
    $.widget('rk.visitPlanCreateDialogCtrl', $.rk.oaDialogCtrl, {
        _calendarType:"normal",
        _userId:"",
        _create:function(){
            var me = this;
            var elem = me.element;
            var temp = require('oa/tmpl/schedule/visit/tpl_schedule_visit_plan_create.tpl');
            var html = rk.templateText(temp,{});
            elem.html(html);
            me._listeners();
        },
        _init: function () {
            var me = this;
            var elem = me.element;
            if(!me._userId){
                me._userId = SESSION.user.id;
            }
            elem.find("[act='visit_plan_repeat_div']").ambassadorCalendarCtrl({userId: me._userId});//{calendarType:"month"}
            elem.find("[act='schedule_visit_start_time']").datepicker({minDate:new Date()});
            elem.find("[act='schedule_visit_end_time']").datepicker({minDate:new Date()});
            //singletreeselector({
            //    source : 'url'
            //})
            elem.find("[act='visit_plan_responsibleId']").val(SESSION.user.name);
            elem.find("[act='visit_plan_responsibleId']").attr("userid",SESSION.user.id);
            elem.find("[act='visit_plan_responsibleId']").rkUser({
                onSelect: function(userId, userName) {
                    elem.find("[act='visit_plan_accountIds']").val('');
                    elem.find("[act='visit_plan_accountIds']").multiaccountselector('val',[]);
                    elem.find("[act='visit_plan_accountIds']").attr("disabled",false);
                    elem.find("[act='visit_plan_accountIds']").attr('placeholder',"请输入并选择");
                    var value = elem.find("[act='visit_plan_responsibleId']").attr("userid");
                    elem.find("[act='visit_plan_accountIds']").multiaccountselector({
                        dataCache:false,
                        source: "/json/crm_visitPlan/getSearchAccount.action?selectUserId="+value, //'/search/u.action?s=m&pageNo=1&key='
                        selectUrl: "/json/crm_visitPlan/getAccountPartnerLevel.action", //"/json/sns_privatemsg/all-departs.action",
                        checkedUrl: "/json/crm_visitPlan/getMyAccountByPartnerLevel.action?selectUserId="+value //"/json/sns_privatemsg/all-depart-user.action",
                    });
                    me._userId = value;
                    if(me._calendarType == "normal"){
                        elem.find("[act='visit_plan_repeat_div']").html("");
                        elem.find("[act='visit_plan_repeat_div']").ambassadorCalendarCtrl({calendarType:"normal",userId:me._userId});
                    }
                }
            });
            elem.find("[act='visit_plan_accountIds']").multiaccountselector({
                //source: '', //'/search/u.action?s=m&pageNo=1&key='
                //departsUrl: '', //"/json/sns_privatemsg/all-departs.action",
                //departsUserUrl: '', //"/json/sns_privatemsg/all-depart-user.action",
                //selectKey:null
                source: "/json/crm_visitPlan/getSearchAccount.action", //'/search/u.action?s=m&pageNo=1&key='
                selectUrl: "/json/crm_visitPlan/getAccountPartnerLevel.action", //"/json/sns_privatemsg/all-departs.action",
                checkedUrl: "/json/crm_visitPlan/getMyAccountByPartnerLevel.action" //"/json/sns_privatemsg/all-depart-user.action",
            });
        },
        _listeners:function(){
            var me = this;
            var elem = me.element;
            me.getBtn('ok').on('click', $.proxy(me.doSave, me));
            me.getBtn('cancel').on('click',function(){
                me.closeMe();//关闭
            });
            elem.find("[act='schedule_visit_frequency']").selectmenu({
                change:function(){
                    var select = $(this);
                    var value = select.val();
                    if(value == 0){
                        elem.find("[act='schedule_visit_start_end_time_li']").hide();
                        elem.find("[act='visit_plan_repeat_div']").html("");
                        elem.find("[act='visit_plan_repeat_div']").ambassadorCalendarCtrl({calendarType:"normal",userId:me._userId});
                        me._calendarType = "normal";
                    }else if(value == 2){
                        elem.find("[act='schedule_visit_start_end_time_li']").show();
                        elem.find("[act='visit_plan_repeat_div']").html("");
                        elem.find("[act='visit_plan_repeat_div']").ambassadorCalendarCtrl({calendarType:"week"});
                        me._calendarType = "week";
                    }else if(value == 3){
                        elem.find("[act='schedule_visit_start_end_time_li']").show();
                        elem.find("[act='visit_plan_repeat_div']").html("");
                        elem.find("[act='visit_plan_repeat_div']").ambassadorCalendarCtrl({calendarType:"month"});
                        me._calendarType = "month";
                    }
                }
            });
            elem.on('keyup',"[act='visit_plan_responsibleId']",function(){
                var responsibleIdInput = elem.find("[act='visit_plan_responsibleId']");
                responsibleIdInput.attr("userid",'');
                var uid = responsibleIdInput.attr("userid");
                var name = responsibleIdInput.val();
                if(!uid){
                    elem.find("[act='visit_plan_accountIds']").multiaccountselector('val',[]);
                    elem.find("[act='visit_plan_accountIds']").multiaccountselector({
                        source: '',
                        departsUrl: '',
                        departsUserUrl: ''
                    });
                    elem.find("[act='visit_plan_accountIds']").attr('placeholder',"请选择负责人");
                    elem.find("[act='visit_plan_accountIds']").attr("disabled",true);
                }
            });
        },
        doSave:function(){
            var me = this;
            var elem = me.element;
            //var value = elem.find("[act='visit_plan_repeat_div']").ambassadorCalendarCtrl('getSelectedDate');
            //var form = elem.find("[act='schedule_visit_plan_create_form']");
            //var formData = form.serializeArray();
            var frequency = elem.find("[act='schedule_visit_frequency']").val();
            var startTime = elem.find("[act='schedule_visit_start_time']").val();
            var endTime = elem.find("[act='schedule_visit_end_time']").val();
            var repeat = elem.find("[act='visit_plan_repeat_div']").ambassadorCalendarCtrl('getSelectedDate');//重复规则选中的时间
            var rules;
            if(repeat.length > 0){
                rules = "";
                $.each(repeat, function(i, value) {
                    rules += value;
                    if(i != repeat.length -1){
                        rules += ',';
                    }
                });
            }
            var responsibleId = elem.find("[act='visit_plan_responsibleId']").attr("userid");//负责人id
            var accountObjects = elem.find("[act='visit_plan_accountIds']").multiaccountselector('val');
            var accountIds = '';
            var dateTimes;
            $.each(accountObjects, function(i, value) {
                if(value && value.value) {
                    accountIds += value.value;
                    if(i != accountObjects.length -1){
                        accountIds += ',';
                    }
                }
            });
            if(!frequency){
                rk.noticeError('请输入重复规则');
                return;
            }
            if(frequency == 0){
                if(!rules){
                    rk.noticeError('请选择日期');
                    return;
                }
                var nowDate = new Date();
                var month = nowDate.getMonth() + 1+"";
                var day = nowDate.getDate() +"";
                var nowDateString = nowDate.getFullYear() + "-" +(month.length == 1 ? "0"+month : month) +"-" +(day.length == 1 ? "0"+day : day) ;

                for(var i=0;i<repeat.length;i++){
                    var value = repeat[i];
                    if(value < nowDateString){
                        rk.noticeError('所选时间不能早于今天');
                        return;
                    }
                }
                dateTimes = rules;
            }
            if(frequency == 2 || frequency == 3){
                if(!startTime || !endTime) {
                    rk.noticeError('请输入起止时间');
                    return;
                }
                if(startTime > endTime){
                    rk.noticeError('开始时间不能晚于结束时间');
                    return;
                }
                var nowDate = new Date();
                var month = (nowDate.getMonth() + 1) +"";
                var day = nowDate.getDate()+"";
                var nowDateString = nowDate.getFullYear() + "-" +(month.length == 1 ? "0"+month : month) +"-" +(day.length == 1 ? "0"+day : day) ;
                if(startTime < nowDateString){
                    rk.noticeError('开始时间不能早于今天');
                    return;
                }
                if(!rules){
                    rk.noticeError('请选择重复时间');
                    return;
                }
            }
            if(!responsibleId){
                rk.noticeError('请填写负责人');
                return;
            }
            if(!accountIds){
                rk.noticeError('请选择负责终端');
                return;
            }

            var param = {};
            if(responsibleId){
                param.responsibleId=responsibleId;
            }
            if(accountIds){
                param.accountIds=accountIds;
            }
            if(frequency){
                param.frequency=frequency;
            }
            if(startTime){
                param.startTime=startTime;
            }
            if(endTime){
                param.endTime=endTime;
            }
            if(rules){
                param.rules=rules;
            }
            if(dateTimes){
                param.dateTimes=dateTimes;
            }
            me.getBtn('ok').beLoading();
            rk.post("/json/crm_visitPlan/save-visit-plan.action",param,function(json){
                if(json.status == 0) {
                    //变更时判断一下哪个处于激活态，传递激活的tab页重新加载数据
                    var viewType;
                    var panel = rk.oa.getPanel();
                    var scheduleDateTypes = panel.find('span[act=scheduleDateType]');
                    for (var i in scheduleDateTypes) {
                        if (scheduleDateTypes.eq(i).hasClass('active')) {
                            if (i == 0) {
                                viewType = 'day';
                            } else if (i == 1) {
                                viewType = 'week';
                            } else if (i == 2) {
                                viewType = 'month';
                            }
                        }
                    }
                    if(startTime) {
                        me._refreshFullcalendar(viewType, startTime);
                    }else{
                        me._refreshFullcalendar(viewType, repeat[0]);
                    }
                    rk.noticeSuccess(rk.i18n("APPS_FILE_SAVE_SUCCESS"));
                    var $taskPanel = $('#index_task_panel');
                    setTimeout(function(){
                        require.async('page/js/index/todaywork/todayWorkCtrl', function() {
                            $taskPanel.todayWorkCtrl();
                        });
                    },1000);
                    me.closeMe();
                }else{
                    me.getBtn('ok').beLoading('delay');
                    rk.noticeError(rk.i18n("APPS_FILE_SAVE_FAILED"));
                }
            });
        },
        _refreshFullcalendar: function(viewType, dateText){
            var me = this;
            require.async(["../schedulePanelCtrl"],function(){
                if(viewType == "day"){
                    rk.oa.getPanel().schedulePanelCtrl('setPreClickDay',dateText);
                } else if(viewType == "week"){
                    rk.oa.getPanel().schedulePanelCtrl('setPreClickDayWeek',dateText);
                } else if(viewType == "month"){
                    rk.oa.getPanel().schedulePanelCtrl('setPreClickDayMonth',dateText);
                }
                if(rk.oa.getContent() && rk.oa.getContent().length > 0) {
                    scheduleService.showFullcalendar(viewType, dateText);
                }
                scheduleUtil.loadEvents();
            });
        }
    });
});